/* eslint-disable jsdoc/no-restricted-syntax */
const END = 1;

/**
 * @type {unique symbol}
 */
const __nil__ = Symbol("__nil__");

export class DFA {
  /**
   * @type {Record<string, any>}
   */
  #arrHashMap = {};

  /**
   * @public
   */
  show() {
    console.dir(this.#arrHashMap, {
      depth: 10,
    });
  }

  /**
   * @public
   * @param {string} str 关键词
   * @returns {void}
   */
  addKeyWord(str) {
    let currentMap = this.#arrHashMap;
    for (const [i, s] of [...str].entries()) {
      const isEnd = i === str.length - 1;
      if (currentMap[s]) {
        if (isEnd) {
          currentMap[s][__nil__] = END;
        }
      } else {
        currentMap[s] = { [__nil__]: isEnd ? END : 0 };
      }
      currentMap = currentMap[s];
    }
  }

  /**
   * @public
   * @param {string} str
   * @returns {boolean}
   */
  searchKey(str) {
    let currentMap = this.#arrHashMap;
    for (const s of str) {
      if (!currentMap[s]) {
        currentMap = this.#arrHashMap;
        continue;
      }
      if (currentMap[s][__nil__] === END) {
        return true;
      }
      currentMap = currentMap[s];
    }
    return false;
  }

  /**
   * @public
   */
  clean() {
    this.#arrHashMap = {};
  }
}
